package com.zchu.rxcache.utils;


import ohos.media.image.ImagePacker;
import ohos.media.image.PixelMap;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;


/**
 * Implements functions useful to check
 * MemorySizeOf usage.
 *
 * @author 赵成柱
 * @since 2021-02-09
 */
public class MemorySizeOf {

    /**
     * Function that get the size of an object.
     *
     * @return Size in bytes of the object or -1 if the object
     * is null.
     *
     * @param serial
     * @return int
     * @throws IOException
     */
    public static int sizeOf(Serializable serial) throws IOException {
        if (serial == null) {
            return 0;
        }
        int size;
        ByteArrayOutputStream baos = null;
        ObjectOutputStream oos = null;
        try {
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(serial);
            oos.flush();  //缓冲流
            size = baos.size();
        } finally {
            Utils.close(oos);
            Utils.close(baos);
        }
        return size;
    }


    public static int sizeOf(PixelMap bitmap) {
        if (bitmap == null) {
            return 0;
        }

        int size;
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            String format = Utils.getFormat(bitmap);
            ImagePacker imagePacker = ImagePacker.create();
            ImagePacker.PackingOptions packingOptions = new ImagePacker.PackingOptions();
            packingOptions.format = format;
            packingOptions.quality = 100;
            packingOptions.numberHint = 1;
            boolean result = imagePacker.initializePacking(baos, packingOptions);
            imagePacker.addImage(bitmap);
            imagePacker.finalizePacking();
            imagePacker.release();
            size = baos.size();
        } finally {
            Utils.close(baos);
        }
        return size;
    }

}















